# _*_ coding: utf-8 _*_
"""
@ 时间    ：2024/10/22 19:16
@ 作者    ：旺财
@ 文件    ：03 多元一次模型.py
@ 说明    ：银行根据多个因素预测客户价值
"""
import pandas as pd
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm

# 1.读取数据
df = pd.read_excel('客户价值数据表.xlsx')
print(df.head())
X = df[['历史贷款金额', '贷款次数', '学历', '月收入', '性别']]
Y = df['客户价值']

# 2.模型搭建
regr = LinearRegression()
regr.fit(X, Y)


# 3.方程构造
def ceof_dec(k, num=0):     # 保留小数位方法
    if abs(k) >= 100.0:
        return int(k) if num == 0 else round(k / 10 ** num, num)
    else:
        new_k = k * 10.0
        new_num = num + 1
        return ceof_dec(new_k, new_num)


k1, k2, k3, k4, k5 = [ceof_dec(x) for x in regr.coef_]
k0 = ceof_dec(regr.intercept_)
equation = f'方程: y = {k1}x₁ + {k2}x₂ + {k3}x₃ + {k4}x₄ + {k5}x₅ + {k0}'.replace('+ -', '- ')
print(equation)

# 4.模型评估    模型的优劣观察参数 R-squared 与 Adj.R-squared
X2 = sm.add_constant(X)
est = sm.OLS(Y, X2).fit()
print('OLS报告')
print(est.summary())